package com.wwwc.index.web.servlet;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.security.*;
import java.io.*;
import java.net.*;

import javax.imageio.*;
import java.awt.image.*;

import com.wwwc.util.web.*;
import com.wwwc.index.web.ejb.database.*;
//import com.wwwc.index.web.database.*;
import com.wwwc.index.web.ejb.*;

public class FileUploadServlet extends HttpServlet
{
    private EJBDatabaseQuery ejbdb;
    public void doPost(HttpServletRequest request,  HttpServletResponse response) {
	DataInputStream       in = null;
	FileOutputStream fileOut = null;
	HttpSession session = request.getSession();
	String user_ip      = request.getRemoteAddr();
	String return_url = null;
	if(session.getAttribute("page_return") != null) {
	    return_url = (String)session.getAttribute("page_return");
	}

	if(return_url == null) {
	    return_url = "ShowImageServlet";
	}

	String error = null;

	try {
	    ResourceBundle SystemInfo = (ResourceBundle)session.getAttribute("SystemInfo");
	    if (SystemInfo == null) return;

	    String local_ips = SystemInfo.getString("3wcenter.local_ips");
	    //String post_home = SystemInfo.getString("3wcenter.default.post.home");
	    String max_size  = SystemInfo.getString("3wcenter.default.post.upload.image.max_size");

	    String contentType = request.getContentType();

	    if(contentType != null && contentType.indexOf("multipart/form-data") != -1) {
		
		in = new DataInputStream(request.getInputStream());
		int formDataLength = request.getContentLength();
		
		if (formDataLength > Integer.parseInt(max_size)) {
		    error = "Your file size is:("+formDataLength+")(Max:"+max_size+")";
		    try {
			request.setAttribute("upload_error",error);
			RequestDispatcher rd = request.getRequestDispatcher(return_url);
			rd.forward(request,response);
			return;
		    }
		    catch (ServletException e) {
			System.out.println("Error:MainBarServlet:101:"+e);
			return;
		    }
		}

		byte dataBytes[]  = new byte[formDataLength];
		int bytesRead      = 0;
		int totalBytesRead = 0;
		int sizeCheck      = 0;
		    
		while (totalBytesRead < formDataLength) {
		    sizeCheck = totalBytesRead + in.available();
		    bytesRead = in.read(dataBytes, totalBytesRead, formDataLength);
		    totalBytesRead += bytesRead;
		}

		String file  = new String(dataBytes);

		int    lastIndex = contentType.lastIndexOf("=");
		String boundary  = contentType.substring(lastIndex+1, contentType.length());
		
		String save_file_name = file.substring(file.indexOf("filename=\"")+10);
		save_file_name = save_file_name.substring(0,save_file_name.indexOf("\n"));
		save_file_name = save_file_name.substring(save_file_name.lastIndexOf("\\")+1,save_file_name.indexOf("\""));
		
		int pos; //position in upload file
		//find position of upload file section of request
		pos = file.indexOf("filename=\"");
		//find position of content-disposition line
		pos = file.indexOf("\n",pos)+1;
		//find position of content-type line
		pos = file.indexOf("\n",pos)+1;
		//find position of blank line
		pos = file.indexOf("\n",pos)+1;
		
		///////////////////////////////////////////////////////////////////////////////////////
		// find the location of the next boundary marker
		// (marking the end of the upload file data)
		///////////////////////////////////////////////////////////////////////////////////////

		int boundaryLocation = file.indexOf(boundary,pos)-4;

		if( boundaryLocation < 5) {
		    dataBytes = null;
		    file      = null;
		    error = "Loding file error!";
		    try {
			request.setAttribute("upload_error",error);
			RequestDispatcher rd = request.getRequestDispatcher(return_url);
			rd.forward(request,response);
			return;
		    }
		    catch (ServletException e) {
			System.out.println("Error:MainBarServlet:101:"+e);
			return;
		    }
		}

		String fileName = save_file_name;
		if(!(save_file_name.toUpperCase().endsWith(".GIF")  || 
		     save_file_name.toUpperCase().endsWith(".JPG")  || 
		     save_file_name.toUpperCase().endsWith(".JPEG") ||
  		     save_file_name.toUpperCase().endsWith(".BMP")  ||
		     save_file_name.toUpperCase().endsWith(".DIB")
		     )) {
		    dataBytes = null;
		    file      = null;
		    error = "Please select *.jpg, *.jpeg, *.gif, or *.bmp file only!";
		    try {
			request.setAttribute("upload_error",error);
			RequestDispatcher rd = request.getRequestDispatcher(return_url);
			rd.forward(request,response);
			return;
		    }
		    catch (ServletException e) {
			System.out.println("Error:MainBarServlet:101:"+e);
			return;
		    }
		}
		
		//////////////////////////////////////////////////////////////////////////////
		// before save file, make sure to check everything
		/////////////////////////////////////////////////////////////////////////////
		if(save_file_name.length()>500) {
		    dataBytes = null;
		    file      = null;
		    error = "File name is too long.";
		    try {
			request.setAttribute("upload_error",error);
			RequestDispatcher rd = request.getRequestDispatcher(return_url);
			rd.forward(request,response);
			return;
		    }
		    catch (ServletException e) {
			System.out.println("Error:MainBarServlet:101:"+e);
			return;
		    }
		}

		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		if(boundaryLocation < pos) {
		    byteOut.write(dataBytes, pos, (dataBytes.length-pos-1));
		}
		else {
		    byteOut.write(dataBytes,pos,(boundaryLocation-pos));
		}
		byte[] test = byteOut.toByteArray();

		if(test.length==0) {
		    error = "Image not found.";
		    try {
			request.setAttribute("upload_error",error);
			RequestDispatcher rd = request.getRequestDispatcher(return_url);
			rd.forward(request,response);
			return;
		    }
		    catch (ServletException e) {
			System.out.println("Error:MainBarServlet:101:"+e);
			return;
		    }
		}

		try {
		    session.setAttribute("image_data",test);
		    test = null;
		    RequestDispatcher rd = request.getRequestDispatcher(return_url);
		    rd.forward(request,response);
		    return;
		}
		catch (ServletException e) {
		    System.out.println("Error:MainBarServlet:101:"+e);
		    return;
		}
	    }
	}
	catch(Exception e) {
	    System.out.println("TestImageUploadServlet["+e+"]");
	    return;
	}
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
    {
	PrintWriter out = response.getWriter();
	HttpSession session = request.getSession(true);
	response.setContentType("text/html");
	StringBuffer sbf = new StringBuffer();
	sbf.append("<HTML><HEAD><TITLE>Upload form</TITLE>");
	sbf.append("</HEAD><BODY><CENTER>");
	sbf.append("<FORM method=post name=upload_image ENCTYPE=multipart/form-data action=TestImageUploadServlet>");
	sbf.append("<TABLE style='font-size:10pt'>");
	sbf.append("<TR><TD style='font-size:12pt'>Upload file:");
	sbf.append("</TD></TR>");
	sbf.append("<TR><TD>");
	sbf.append("<INPUT TYPE='FILE' NAME='Filename' VALUE='' MAXLENGTH=255 SIZE=70 style='font-size: 8pt'>");
	sbf.append("<INPUT TYPE='SUBMIT' name='B1' Value='Attach' style='font-size: 8pt'>");
	sbf.append("</TD></TR></TABLE>");
	sbf.append("</FORM>");
	sbf.append("</CENTER></BODY></HTML>");
	out.println(sbf);
    }
}

